package com.example.common.handler;

import com.example.common.exception.ResponseException;
import com.example.common.response.ServerResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Description: 响应增强
 * @Auther: Swain
 * @Date: 2021/1/11 16:48
 * @Version 1.0.0
 */
@RestControllerAdvice(basePackages = {"com.example.controller"})
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 如果接口返回的类型本身就是ServerResponse，那就没有必要进行额外的操作，返回false
     */
    @Override
    public boolean supports(MethodParameter returnType,
        Class<? extends HttpMessageConverter<?>> aClass) {
        boolean flag = returnType.getParameterType().equals(ServerResponse.class);
        return !flag;
    }

    /**
     * 响应返回之前的操作，将未封装的响应封装成ServerResponse后返回
     */
    @Override
    public Object beforeBodyWrite(Object data,
        MethodParameter returnType,
        MediaType mediaType,
        Class<? extends HttpMessageConverter<?>> aClass,
        ServerHttpRequest request,
        ServerHttpResponse response) {
        // String类型不能直接包装，所以要进行些特别的处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 将数据包装在ServerResponse里后，再转换为json字符串响应给前端
                return objectMapper.writeValueAsString(ServerResponse.createBySuccess(data));
            } catch (JsonProcessingException e) {
                throw new ResponseException("String类型转json字符串发生错误");
            }
        }
        // 将原本的数据包装在ServerResponse里
        return ServerResponse.createBySuccess(data);
    }


}
